package cn.sylinx.horm.core.datasource;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.sylinx.horm.core.DynamicClient;
import cn.sylinx.horm.dialect.DbType;

public class NamedDataSource {

    private static final Logger logger = LoggerFactory.getLogger(NamedDataSource.class);

    public static final String CURRENT_DATASOURCE_NAME = "current_datasource_name"; //当前数据源名称

    private DataSource dataSource;
    private String dataSourceName;
    private DbType dbType;

    public NamedDataSource() {
        this.dataSourceName = DynamicClient.DEFAULT_DS_NAME;
    }

    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public String getDataSourceName() {
        return dataSourceName;
    }

    public void setDataSourceName(String dataSourceName) {
        this.dataSourceName = dataSourceName;
    }

    public DbType getDbType() {
        return dbType;
    }

    public void setDbType(DbType dbType) {
        this.dbType = dbType;
    }

    public void close() {
        boolean ok = DataSourceShutterManager.INSTANCE.close(dataSource);
        if (ok) {
            logger.info("The datasource -> {}, type -> {} closed", dataSourceName, dbType.getValue());
        }
    }

    public static NamedDataSource create(DataSource dataSource, String dataSourceName, DbType dbType) {
        NamedDataSource nds = new NamedDataSource();
        nds.setDataSource(dataSource);
        nds.setDataSourceName(dataSourceName);
        nds.setDbType(dbType);
        return nds;
    }

    @Override
    public String toString() {
        return "NamedDataSource [dataSource=" + dataSource + ", dataSourceName=" + dataSourceName + ", dbType=" + dbType
                + "]";
    }

}